package com.wxy.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxy.school.common.Constant;
import com.wxy.school.common.R;
import com.wxy.school.dto.EmployeeDto;
import com.wxy.school.entity.Employee;
import com.wxy.school.service.EmployeeService;
import com.wxy.school.utils.BaseContext;
import com.wxy.school.utils.SMSUtils;
import com.wxy.school.utils.ValidateCodeUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/school")

public class EmployeeController {

    @Resource
    private EmployeeService employeeService;

    /**
     * @description: 登录
     * @author: 王祥宇
     * @param: session
     * @param: employee
     * @return: com.wxy.school.common.R<com.wxy.school.entity.Employee>
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest httpServletRequest, @RequestBody Employee employee){
        // 获取前端传过来的密码
        String password = employee.getPassword();
        System.out.println(password);

        // 对传过来的密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 创建查询条件
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getUserName, employee.getUserName());
        // 调用Service层方法进行条件查询
        Employee emp = employeeService.getOne(lambdaQueryWrapper);
        // 判断用户是否存在
        if(emp == null){
            return R.error("登陆失败，用户不存在");
        }
        // 判断密码是否正确
        if (!emp.getPassword().equals(password)){
            return R.error("登陆失败，用户密码错误");
        }
        // 判断帐号状态是否正常
        if (emp.getStatus() == 0){
            return R.error("登陆失败，用户已被禁用");
        }
        // 存储用户信息到Session中
        httpServletRequest.getSession().setAttribute("employee", emp.getUserName());
        //创建EmployeeDto对象，并将emp中数据拷贝给employeeDto
        EmployeeDto employeeDto = new EmployeeDto();
        BeanUtils.copyProperties(emp, employeeDto);
        //使用UUID生成一个token并赋值给employeeDto对象中token属性
        employeeDto.setToken(UUID.randomUUID().toString());

        // 返回用户信息
        return R.success(employeeDto);
    }

    /**
     * @description: 发送验证码
     * @author: 王祥宇
     * @param: employee
     * @param: servletRequest
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PostMapping("/loginWithPhone")
    public R<String> loginWithPhone(@RequestBody Employee employee, HttpServletRequest servletRequest){
        System.out.println(employee);
        //获取手机号
        String phone = employee.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //查询用户信息
            LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Employee::getPhone, phone);
            Employee emp = employeeService.getOne(lambdaQueryWrapper);
            //判断用户是否存在
            if (emp == null){
                return R.error("此用户不存在,请检查手机号是否输入正确");
            }else{
                //生成随机验证码
                String code = ValidateCodeUtils.generateValidateCode(4).toString();
                //发送短信
                SMSUtils.sendMessage(Constant.SIGN_NAME, Constant.TEMPLATE_CODE, phone, code);
                log.info("code={}",code);

                //存储验证码
                servletRequest.getSession().setAttribute("code", code);
                return R.success("短信发送成功");
            }
        }else {
            return R.error("短信发送失败");
        }
    }

    /**
     * @description: 对比验证码
     * @author: 王祥宇
     * @param: map
     * @param: servletRequest
     * @return: com.wxy.school.common.R<com.wxy.school.entity.Employee>
     */
    @PostMapping("/loginWithCode")
    public R<Employee> loginWithCode(@RequestBody Map map, HttpServletRequest servletRequest){
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //获取保存好的验证码
        Object attribute = servletRequest.getSession().getAttribute("code");

        //对比验证码
        if (attribute != null && attribute.equals(code)){
            //查询用户信息
            LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Employee::getPhone, phone);
            Employee emp = employeeService.getOne(lambdaQueryWrapper);
            //创建EmployeeDto对象，并将emp中数据拷贝给employeeDto
            EmployeeDto employeeDto = new EmployeeDto();
            BeanUtils.copyProperties(emp, employeeDto);
            //使用UUID生成一个token并赋值给employeeDto对象中token属性
            employeeDto.setToken(UUID.randomUUID().toString());
            //返回用户信息
            return R.success(employeeDto);
        }else {
            return R.error("验证码错误");
        }
    }
    /**
     * @description: 获取所有用户的信息
     * @author: 王祥宇
     * @param: pageNum 查询页数
     * @param: pageSize 每页查询的条数
     * @param: qurey 模糊查询参数
     * @return: com.wxy.school.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     */
    @GetMapping("/employeeList")
    public R<Page> page(int pageNum, int pageSize,String qurey){
        //构建分页查询器
        Page pageInfo = new Page(pageNum, pageSize);
        //构建查询条件
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据输入框内容模糊查寻  当qurey不为空时添加该条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(qurey), Employee::getUserName, qurey);
        //添加排序查询  根据用户账号的创建时间
        lambdaQueryWrapper.orderByAsc(Employee::getCreateTime);
        //执行查询
        employeeService.page(pageInfo,lambdaQueryWrapper);
        //返回查询的结果
        return R.success(pageInfo);
    }

    /**
     * @description: 添加用户信息
     * @author: 王祥宇
     * @param: employeeDto
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PostMapping("/addUser")
    public R<String> addEmployee(@RequestBody EmployeeDto employeeDto){
        //创建employee对象，将employeeDto中数据拷贝给employee
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDto, employee, "username");
        //将用户名存储到线程中
        BaseContext.setThreadLocal(employeeDto.getUsername());
        //生成用户初始密码
        //将加密后的用户密码存入employee对象
        employee.setPassword(DigestUtils.md5DigestAsHex("156832zxc@".getBytes()));
        //创建查询条件，判断用户是否已经存在
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getUserName, employee.getUserName());
        Employee employee1 = employeeService.getOne(lambdaQueryWrapper);
        //如果用户已经存在则返回错误信息，不存在将用户添加到数据库
        if (employee1 == null){
            employeeService.save(employee);
            return R.success("添加用户成功");
        }else {
            return R.error("用户添加失败");
        }
    }

    /**
     * @description: 根据id进行查询
     * @author: 王祥宇
     * @param: id
     * @return: com.wxy.school.common.R<com.wxy.school.entity.Employee>
     */
    @GetMapping("employee/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        if (employee != null){
            return R.success(employee);
        }else {
            return R.error("查询失败");
        }
    }

    /**
     * @description: 更新用户信息
     * @author: 王祥宇
     * @param: employeeDto
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PutMapping("/updateEmployee")
    public R<String> updateEmployee(@RequestBody EmployeeDto employeeDto){
        //创建employee对象，将employeeDto中数据拷贝给employee
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDto, employee, "username");
        //将用户名存储到线程中
        BaseContext.setThreadLocal(employeeDto.getUsername());

        employeeService.updateById(employee);
        return R.success("用户信息修改成功");
    }

    /**
     * @description: 修改用户密码
     * @author: 王祥宇
     * @param: employee
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PutMapping("/updateEmployeePassword")
    public R<String> updatePassword(@RequestBody Employee employee){
        //将用户名存储到线程中
        BaseContext.setThreadLocal(employee.getUserName());
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        employeeService.updateById(employee);
        return R.success("用户密码修改成功,请重新进行登录");
    }

    /**
     * @description: 删除用户信息
     * @author: 王祥宇
     * @param: id
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @DeleteMapping("delete/{id}")
    public R<String> deleteEmployee(@PathVariable Long id){
        employeeService.removeById(id);
        return R.success("删除用户信息成功");
    }

    /**
     * @description: 根据手机号查询用户信息
     * @author: 王祥宇
     * @param: phone
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @GetMapping("/getByPhone/{phone}")
    public R<String> getByPhone(@PathVariable String phone){
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getPhone, phone);
        Employee employee = employeeService.getOne(lambdaQueryWrapper);
        if (employee == null){
            return R.error("该用户不存在，请检查手机号是否输入正确");
        }else {
            return R.success("success");
        }
    }

}
